using B.S.Medical.Api.Read.Application.Command.Patient;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Medical;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Patient
{
    /// <summary>
    /// 获取患者信息处理器
    /// </summary>
    public class GetPatientHandler : IRequestHandler<GetPatientCommand, ApiPageing<PatientDTO>>
    {
        private readonly IBaseRepository<PatientModel> patientRepo;
        private readonly ILogger<GetPatientHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="patientRepo">患者仓储</param>
        /// <param name="logger">日志</param>
        public GetPatientHandler(
            IBaseRepository<PatientModel> patientRepo,
            ILogger<GetPatientHandler> logger)
        {
            this.patientRepo = patientRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取患者信息请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>患者信息分页结果</returns>
        public Task<ApiPageing<PatientDTO>> Handle(GetPatientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiPageing<PatientDTO> res = new ApiPageing<PatientDTO>();
                
                // 获取所有未删除的患者数据
                var patients = patientRepo.GetAll().Where(a => !a.IsDeleted);
                // 条件判断账号ID
                if(request.AccountId != 0)
                {
                    patients = patients.Where(a => a.AccountId == request.AccountId);
                }
                
                // 转换为DTO
                var query = from patient in patients
                            select new PatientDTO
                            {
                                Id = patient.Id,
                                Name = patient.Name,
                                IdCard = patient.IdCard,
                                Relation = patient.Relation,
                                AccountId = patient.AccountId
                            };

                // 计算总数
                int totalCount = query.Count();
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 分页处理
                var items = query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                // 构建返回结果
                res.Code = ApiEnum.Success;
                res.Msg = "获取患者列表成功";
                res.PageData = items;
                res.TotaCount = totalCount;
                res.TotaPage = totalPage;

                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取患者列表时发生错误");
                return Task.FromResult(new ApiPageing<PatientDTO>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取患者列表失败：" + ex.Message
                });
            }
        }
    }
} 